<?php include("php/dao/DatabaseDAO.php");
include("php/dao/XMLFeedDAO.php");
include("php/dao/UserFeedDAO.php");
include("php/Security.php");

Security::checkAuthenticated();

$xmlFeedId = $_GET["xmlFeedId"];

$xmlFeedDAO = new XMLFeedDAO();
$databaseDAO = new DatabaseDAO();
$userFeedDAO = new UserFeedDAO();
$xmlFeed = $xmlFeedDAO->getXMLFeed($xmlFeedId);
$database = $databaseDAO->getDatabase($xmlFeed["DatabaseId"]);

$xmlTableMapping = $xmlFeedDAO->getPrimaryXMLTableMapping($xmlFeedId);
$xmlSecondaryTableMapping = $xmlFeedDAO->getSecondaryXMLTableMapping($xmlFeedId);

$xmlColumnMappingList = $xmlFeedDAO->getXMLColumnMapping($xmlTableMapping["Id"]);

$mappingColumn = $xmlFeedDAO->getMappingColumn($xmlTableMapping["Id"]);
$keyColumn = $xmlFeedDAO->getKeyColumn($xmlFeedId);

$columnsList = $databaseDAO->getTableColumns($xmlFeed["DatabaseId"], $xmlTableMapping["Table"]);

$databaseTables = $databaseDAO->getDatabasesTables($xmlFeed["DatabaseId"]);

$listOfActionsSelect = $userFeedDAO->getActions($_SESSION["UserId"]);
$listOfActions = Array();

while ($row = mysqli_fetch_assoc($listOfActionsSelect)) {
    $listOfActions[] = $row;
}

/**
 * @param $column
 * @param $keyColumn
 * @return string
 */
function getSelected($column, $keyColumn)
{
    $selected = "";
    if ($column == $keyColumn) {
        $selected = " selected = 'selected' ";
        return $selected;
    }
    return $selected;
}

?>

<!DOCTYPE html>
<html>
<head>
    <title>Edit User Xml Feed</title>

    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <link rel="stylesheet" href="css/style.css"/>
    <link rel="stylesheet" href="css/jquery.snippet.css"/>
    <script type="text/javascript" src="js/sh_xml.js"></script>

    <script type="text/javascript" src="js/jquery.snippet.js"></script>
    <script type="text/javascript" src="js/user.functions.js"></script>
</head>
<body>
<h1><a href="manage.php">Manage feeds</a> | <a href="add_new_database.php">Manage Databases</a></h1>

<h2>Edit user XML feed:</h2>


<script>
    var count = 1;
    var secondaryTableCount = 0;
    var mappingKeySet = false;

    $(document).ready(function () {
        var url = $("#feedUrl").val();
        var rootItem = $("#xmlRootItem").val();
        $.ajax({
            dataType: "xml",
            url: "php/LoadXMLFile.php",
            data: {fileUrl: url, xmlRootItem: rootItem},
            type: "POST",
            success: function (xml) {
                $("#xmlPreview").text((new XMLSerializer()).serializeToString(xml));
                $("pre.xmlCode").snippet("xml");

                populateSelect(xml, rootItem, function (optionName, option) {
                    $(".baseSecondaryXmlFields").append(option.clone());

                    $("div").find(".xmlFields").each(function (index, element) {
                        var optionElement = $(element).find("option[value='" + optionName + "']");
                        if (optionElement.length == 0) {
                            $(element).append(option.clone());
                        }
                    });

                    $("div").find(".secondaryXmlFields").each(function (index, element) {
                        var optionElement = $(element).find("option[value='" + optionName + "']");
                        if (optionElement.length == 0) {
                            $(element).append(option.clone());
                        }
                    });
                });
            },
            error: function (error) {
                $("#error").html(error.responseText);
            }
        });

        $("#addNewColumnMapping").click(function () {
            var wrapper = $("#mappingFieldsWrapper").clone();
            wrapper.attr("id", "mappingFieldsWrapper" + count);

            count++;
            $("#mappingWrapper").append(wrapper);
            wrapper.find(".tableColumns").focus();
        });

        $("#addSecondaryTableMapping").click(function () {
            secondaryTableCount++;
            var wrapper = $("#secondaryMappingWrapper").clone();
            wrapper.css("display", "auto");
            wrapper.attr("id", "secondaryMappingWrapper" + secondaryTableCount);
            $("#secondaryTableMappingWrapper").append(wrapper);
        });

        $("#saveFeedForm").submit(function (event) {
            event.preventDefault();

            // get all the inputs into an array.
            var $inputs = $('#mappingWrapper :input');

            // not sure if you wanted this, but I thought I'd add it.
            // get an associative array of just the values.
            var values = [];
            $inputs.each(function () {
                values.push($(this).val());
            });

            var data = getFormattedData(values, false);
            if (!mappingKeySet) {
                alert("You should seelect mapping key from one of mapping columns!");
                return;
            }
            var keyColumn = $("#keyColumn").val();
            var url = $("#feedUrl").val();
            var feedName = $("#feedName").val();
            var xmlRootItem = $("#xmlRootItem").val();
            var databaseId = $("#feedDatabaseId").val();
            var table = $("#feedTable").val();
            var repeatTime = $("#repeatTime").val();
            var secondaryTablesMappings = getSecondaryTablesMappings();
            $.ajax({
                dataType: "html",
                url: "php/CreateXMLFeed.php",
                data: {data: data,
                    secondaryTablesMappings: secondaryTablesMappings,
                    xmlRootItem: xmlRootItem,
                    databaseId: databaseId,
                    feedUrl: url,
                    feedName: feedName,
                    feedTable: table,
                    keyColumn: keyColumn,
                    repeatTime: repeatTime,
                    xmlFeedId: <?php echo $xmlFeedId;?>},
                type: "POST",
                success: function (text) {
                    window.location.href = "manage.php";
                },
                error: function (error) {
                    $("#error").html(error.responseText);
                }
            });
        });
    });

    function removeXmlFieldMapping(item) {
        removeBlock(item, "mappingFieldsWrapper");
    }

    function removeBlock(item, id) {
        if (item.parentNode.id == id) {
            alert("You can't delete first item!");
            return;
        }
        item.parentNode.parentNode.removeChild(item.parentNode);
    }

    function addSecondaryColumnMappingClick(item) {
        var mappingFieldsBlock = $("#" + item.parentNode.id + " #secondaryMappingFieldsWrapper");
        mappingFieldsBlock.last().after(mappingFieldsBlock.first().clone());
    }

    function secondaryTableMappingRemove(item) {
        item.parentNode.parentNode.removeChild(item.parentNode);
    }

    function secondaryRemoveXmlFieldMapping(item, id) {
        item.parentNode.parentNode.removeChild(item.parentNode);

    }

    function secondaryTableChange(select) {
        if (!$(select).val()) {
            return;
        }
        var secondaryTableIndex = select.parentNode.id.substring(select.parentNode.id.length - 1);
        var databaseId = <?php echo $database["Id"]?>;
        var table = select.value;

        function fillTableSelect(items, tableColumns) {
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                tableColumns.append($("<option value='" + item + "'>" + item + "</option>"));
            }
        }

        $.ajax({
            dataType: "json",
            url: "php/GetTableColumns.php",
            data: {databaseId: databaseId, table: table},
            type: "POST",
            success: function (items) {
                var id = "#secondaryMappingWrapper" + secondaryTableIndex;
                $(id + " #secondaryTableColumns").each(function () {
                    $(this).empty();
                    fillTableSelect(items, $(this));
                });
                $(id + " #secondaryDependsOn").each(function () {
                    $(this).empty();
                    $(this).append($("<option value=''></option>"));
                    fillTableSelect(items, $(this));
                });
            },
            error: function (error) {
                $("#error").html(error.responseText);
            }
        });
    }
</script>

<div id="addFeedFormContainer" style="">
    <form id="addFeedForm" action="" method="post">
        <label>Name:</label>
        <input type="text" name="feedName" id="feedName" placeholder="Input feed name" value="<?php
        echo $xmlFeed["Name"];
        ?>" required/></br>

        <label>URL:</label>
        <input type="url" name="feedUrl" id="feedUrl" placeholder="Input feed URL" value="<?php
        echo $xmlFeed["URL"];
        ?>" required/></br>

        <label>Root item:</label>
        <input type="text" name="xmlRootItem" id="xmlRootItem" placeholder="Input root item" value="<?php
        echo $xmlFeed["XmlRootItem"];
        ?>" required/></br>

        <label>Database:</label>
        <input id="feedDatabase" type="text" value="<?php
        echo $database["DatabaseName"];
        ?>" disabled/>

        <input id="feedDatabaseId" type="hidden" value="<?php
        echo $database["Id"];
        ?>" disabled/>
        </br>

        <label>Table:</label>
        <input id="feedTable" type="text" value="<?php
        echo $xmlTableMapping["Table"];
        ?>" disabled></br>

        <label>Repeat days:</label>
        <input id="repeatTime" type="number" value="<?php
        echo $xmlFeed["RepeatTime"];
        ?>"/></br>
    </form>
</div>

<div id="xmlDatabaseMapping" style="width: 100%;">
    <h2>Map columns to XML fields</h2>

    <div id="fieldsMappingContainer" style="width: 600px;">
        <form id="saveFeedForm" action="#" method="POST">
            <div id="mappingWrapper">
                <label>Primary key column:</label>
                <select id="keyColumn" class="keyColumn" name="keyColumn" required>
                    <?php
                    foreach ($columnsList as $column) {
                        echo "<option value='" . $column . "' " . getSelected($column, $keyColumn) . ">" . $column . "</option>";
                    }
                    ?>
                </select></br>
                <label>Mapping column:</label>
                <select id="mappingColumn" class="mappingColumn" name="mappingColumn" required>
                    <?php
                    foreach ($columnsList as $column) {
                        echo "<option value='" . $column . "' " . getSelected($column, $mappingColumn) . ">" . $column . "</option>";
                    }
                    ?>
                </select></br>
                <hr class="style-one"/>
                <?php
                $i = 0;
                foreach ($xmlColumnMappingList as $mapping) {
                    if ($i == 0) {
                        echo '<div id="mappingFieldsWrapper">';
                    } else {
                        echo '<div id="mappingFieldsWrapper' . $i . '">';
                    }
                    echo '<label>Database column:</label>
                    <select id="tableColumns" class="tableColumns" name="tableColumn_0">';
                    foreach ($columnsList as $column) {
                        echo "<option value='" . $column . "' " . getSelected($column, $mapping["DatabaseColumn"]) . ">" . $column . "</option>";
                    }
                    echo '</select></br>';

                    echo '<label>Xml item:</label>
                    <select id="xmlFields" class="xmlFields" name="xmlField_0">';
                    if ($mapping["XmlValueType"] != "value") {
                        $xmlField = $mapping["XmlField"];
                        if ($mapping["XmlValueType"] == "attribute") {
                            $xmlField .= "(attribute)";
                        }
                        echo "<option value='" . $xmlField . "' selected='selected'>" . $xmlField . "</option>";
                    }
                    echo '</select></br>';

                    echo '<label>Custom action:</label>
                    <select id="actions" class="actions" name="action_0">
                    <option value=""></option>';
                    foreach ($listOfActions as $column) {
                        echo "<option value='" . $column['Id'] . "' " . getSelected($column['Id'], $mapping["ActionId"]) . ">" . $column['Description'] . "</option>";
                    }
                    echo '</select></br>';

                    echo '<label>Default value:</label>
                    <input id="defaultValue" class="defaultValue" type="text" name="defaultValue_0"
                           placeholder="Input default value" value="' . $mapping["Default"] . '"/></br>';

                    echo '<label>Plain value:</label>
                    <input id="plainValue" class="plainValue" type="text" name="plainValue_0"
                           placeholder="Input plain value if needed" value="';
                    if ($mapping["XmlValueType"] == "value") {
                        echo $mapping["XmlField"];
                    }
                    echo '"/></br>';

                    echo '<label>Depends on:</label>
                    <select id="dependsOn" class="dependsOn" name="dependsOn_0">
                    <option value=""></option>';
                    foreach ($columnsList as $column) {
                        echo "<option value='" . $column . "' " . getSelected($column, $mapping["DependsOn"]) . ">" . $column . "</option>";
                    }
                    echo '</select></br>';

                    echo '<label>XML tag index:</label>
                    <input id="xmlTagIndex" class="xmlTagIndex" type="number" name="xmlTagIndex_0"
                           placeholder="Input XML tag index" value="' . $mapping["TagIndex"] . '"/></br>';

                    echo '<a id="removeItemLink" name="removeItemLink_0" href="#"
                       onclick="removeXmlFieldMapping(this)">remove</a>';
                    echo '<hr class="style-one"/>';
                    echo '</div>';

                    $i++;
                }
                ?>
            </div>
            <input id="addNewColumnMapping" type="button" class="button" value="Add new...">

            <div id="secondaryTableMappingWrapper">
                <?php
                $j = 0;
                foreach ($xmlSecondaryTableMapping as $secondaryTableMapping) {
                    $xmlSecondaryColumnMappingList = $xmlFeedDAO->getXMLColumnMapping($secondaryTableMapping["Id"]);

                    echo '<div id="secondaryMappingWrapper' . $j . '">
                          <label>Secondary table:</label>
                          <select id="secondaryTable" class="secondaryTable" name="secondaryTable_0"
                                onchange="secondaryTableChange(this)" required>';
                    foreach ($databaseTables as $table) {
                        echo '<option value=""></option>';
                        echo "<option value='" . $table . "' " . getSelected($table, $secondaryTableMapping["Table"]) . ">" . $table . "</option>";
                    }
                    echo '</select></br>
                          <hr class="style-one"/>';

                    foreach ($xmlSecondaryColumnMappingList as $mapping) {
                        echo '<div id="secondaryMappingFieldsWrapper">';
                        echo '<label>Database column:</label>
                    <select id="secondaryTableColumns" class="secondaryTableColumns" name="secondaryTableColumns_0">';
                        $secondaryColumnsList = $databaseDAO->getTableColumns($xmlFeed["DatabaseId"], $secondaryTableMapping["Table"]);
                        foreach ($secondaryColumnsList as $column) {
                            echo "<option value='" . $column . "' " . getSelected($column, $mapping["DatabaseColumn"]) . ">" . $column . "</option>";
                        }
                        echo '</select></br>';

                        echo '<label>Xml item:</label>
                    <select id="secondaryXmlFields" class="secondaryXmlFields" name="secondaryXmlFields_0">';
                        if ($mapping["XmlValueType"] != "value") {
                            $xmlField = $mapping["XmlField"];
                            if ($mapping["XmlValueType"] == "attribute") {
                                $xmlField .= "(attribute)";
                            }
                            echo "<option value='" . $xmlField . "' selected='selected'>" . $xmlField . "</option>";
                        }
                        echo '</select></br>';

                        echo '<label>Custom action:</label>
                    <select id="secondaryActions" class="secondaryActions" name="secondaryActions_0">
                    <option value=""></option>';
                        foreach ($listOfActions as $column) {
                            echo "<option value='" . $column['Id'] . "' " . getSelected($column['Id'], $mapping["ActionId"]) . ">" . $column['Description'] . "</option>";
                        }
                        echo '</select></br>';

                        echo '<label>Default value:</label>
                    <input id="secondaryDefaultValue" class="secondaryDefaultValue" type="text" name="secondaryDefaultValue_0"
                           placeholder="Input default value" value="' . $mapping["Default"] . '"/></br>';

                        echo '<label>Plain value:</label>
                    <input id="secondaryPlainValue" class="secondaryPlainValue" type="text" name="secondaryPlainValue_0"
                           placeholder="Input plain value if needed" value="';
                        if ($mapping["XmlValueType"] == "value") {
                            echo $mapping["XmlField"];
                        }
                        echo '"/></br>';

                        echo '<label>Depends on:</label>
                    <select id="secondaryDependsOn" class="secondaryDependsOn" name="secondaryDependsOn_0">
                    <option value=""></option>';
                        foreach ($columnsList as $column) {
                            echo "<option value='" . $column . "' " . getSelected($column, $mapping["DependsOn"]) . ">" . $column . "</option>";
                        }
                        echo '</select></br>';

                        echo '<label>XML tag index:</label>
                    <input id="secondaryXmlTagIndex" class="secondaryXmlTagIndex" type="number" name="secondaryXmlTagIndex_0"
                           placeholder="Input XML tag index" value="' . $mapping["TagIndex"] . '"/></br>';

                        echo '<a id="secondaryRemoveItemLink" name="secondaryRemoveItemLink_0" href="#"
                       onclick="secondaryRemoveXmlFieldMapping(this)">remove secondary</a>';
                        echo '<hr class="style-one"/>';
                        echo '</div>';
                        echo '<input id="addSecondaryColumnMapping" type="button" class="wideButton"
           value="Add secondary column..." onclick="addSecondaryColumnMappingClick(this)">
    <input id="removeSecondaryTableMapping" type="button" class="wideButton"
           value="Remove secondary table..." onclick="secondaryTableMappingRemove(this)">';

                        $j++;
                    }
                    echo '</div>';
                }
                ?>
            </div>
            <input id="addSecondaryTableMapping" type="button" class="wideButton" value="Add secondary table...">

            <input id="saveFeedButton" type="submit" class="button" value="Save feed">
        </form>
    </div>
    <div id="xmlPreviewContainer" style="width: 600px;">
        <pre id="xmlPreview" class="xmlCode"></pre>
    </div>
</div>
<div id="error"></div>
<div id="secondaryMappingWrapper" style="display: none;">
    <label>Secondary table:</label>
    <select id="secondaryTable" class="secondaryTable" name="secondaryTable_0"
            onchange="secondaryTableChange(this)" required>
        <option value=""></option>
        <?php
        foreach ($databaseTables as $table) {
            echo "<option value=" . $table . ">" . $table . "</option>";
        }
        ?>
    </select></br>
    <hr class="style-one"/>
    <div id="secondaryMappingFieldsWrapper">
        <label>Database column:</label>
        <select id="secondaryTableColumns" class="secondaryTableColumns" name="secondaryTableColumn_0">

        </select></br>
        <label>Xml item:</label>
        <select id="secondaryXmlFields" class="baseSecondaryXmlFields" name="secondaryXmlField_0">

        </select></br>
        <label>Custom action:</label>
        <select id="secondaryActions" class="secondaryActions" name="secondaryAction_0">
            <option value=""></option>
            <?php
            foreach ($listOfActions as $column) {
                echo "<option value=" . $column['Id'] . ">" . $column['Description'] . "</option>";
            }
            ?>
        </select></br>
        <label>Default value:</label>
        <input id="secondaryDefaultValue" class="secondaryDefaultValue" type="text"
               name="secondaryDefaultValue_0"
               placeholder="Input default value"/></br>
        <label>Plain value:</label>
        <input id="secondaryPlainValue" class="secondaryPlainValue" type="text"
               name="secondaryPlainValue_0"
               placeholder="Input plain value if needed"/></br>
        <label>Depends on:</label>
        <select id="secondaryDependsOn" class="secondaryDependsOn" name="secondaryDependsOn_0">

        </select></br>
        <label>XML tag:</label>
        <input id="secondaryXmlTagIndex" class="secondaryXmlTagIndex" type="number"
               name="secondaryXmlTagIndex_0"
               placeholder="Input XML tag index"/></br>
        <a id="secondaryRemoveItemLink" name="secondaryRemoveItemLink_0" href="#"
           onclick="secondaryRemoveXmlFieldMapping(this)">remove secondary</a>
        <hr class="style-one"/>
    </div>
    <input id="addSecondaryColumnMapping" type="button" class="wideButton"
           value="Add secondary column..." onclick="addSecondaryColumnMappingClick(this)">
    <input id="removeSecondaryTableMapping" type="button" class="wideButton"
           value="Remove secondary table..." onclick="secondaryTableMappingRemove(this)">
</div>

</body>
</html>